package com.xgf.exception.handler;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.xgf.common.xgfcommon.result.ResponseBo;
import com.xgf.exception.handler.exception.ServiceException;

import lombok.extern.slf4j.Slf4j;



/**  
 * 
 * @author xgf
 * @date 2020年3月2日  
 */
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class GlobalExceptionHandler {


	@ExceptionHandler(ServiceException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public ResponseBo handleServiceException(ServiceException e) {
		log.error("公共异常处理,监听到ServiceException,异常信息为:{}",e.getMessage());
		return ResponseBo.error(e.getErrcode(), e.getErrMsg());
	}
	
	@ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public ResponseBo handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
		log.error("公共异常处理,监听到HttpMessageNotReadableException,异常信息为:{}",e.getMessage());
		return ResponseBo.error(500, "请求数据格式不正确，请核实后重新提交！");
	}
	
	@ExceptionHandler(ValidationException.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public ResponseBo handlerValidationException(ValidationException e) {
		log.error("公共异常处理,监听到HttpMessageNotReadableException,异常信息为:{}",e.getMessage());
		return ResponseBo.error(500, "请求数据格式不正确，请核实后重新提交！");
	}

	@ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public ResponseBo handleException(Exception e) {
		
		if(e instanceof MethodArgumentNotValidException) {
			MethodArgumentNotValidException e1 = (MethodArgumentNotValidException) e;
			log.debug("MethodArgumentNotValidException ---> :"+e1.toString());
		}
		if (e instanceof ValidationException) {
			ValidationException e1 = (ValidationException) e;
			log.debug("ValidationException ---> :"+e1.toString());
		}
		if (e instanceof ConstraintViolationException) {
			ConstraintViolationException e1 = (ConstraintViolationException) e;
			log.debug("ConstraintViolationException ---> :"+e1.toString());
		}
		
		log.error("公共异常处理,监听到系统异常,异常信息为:{}",e.getMessage());
		return ResponseBo.error(500, "系统异常！");
	}

}
